import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/material.dart';
import 'package:video/common/apis/apis.dart';
import 'package:video/common/entitys/entitys.dart';
import 'package:video/common/utils/http.dart';
import 'package:video/common/values/values.dart';
import 'package:video/common/views/common/error_view.dart';
import 'package:video/common/views/common/progress_view.dart';

class VideoPage extends StatefulWidget {
  VideoPage({Key key}) : super(key: key);

  @override
  _VideoPageState createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoPage> {
  Future<void> _future;
  // 视频播放器
  final FijkPlayer videoPlayer = FijkPlayer();
  // 定义按钮集合
  List buttonList;

  /// 初始化数据
  Future<void> _getUrlAndReadyToPlay() async {
    //根据场站名称获取监控id
    //var idValue = await CppeApi.getTree("庆咸输油站");
    //请求监控流播放地址

    R result =
        await VideoAPI.getVideoUrl(context: context, id: 3, type: "http");
    if (HttpUtil().success(result)) {
      await videoPlayer.setDataSource(result.data.toString(), autoPlay: true);
    }
  }

  /// 初始化播放器
  _initPlayer(FijkPlayer player, Size size) {
    return FijkView(
      width: size.width,
      color: Colors.black,
      onDispose: (data) {},
      panelBuilder: (player, data, context, viewSize, texturePos) {
        return Container(
          width: viewSize.width,
          height: viewSize.height,
        );
      },
      player: player,
    );
  }

  /// 初始化数据
  _initData() {
    _future = _getUrlAndReadyToPlay();
    //初始化按钮集合数据
    buttonList = [
      {
        "title": "向上",
        "predict": 1,
      },
      {
        "title": "向下",
        "predict": 2,
      },
      {
        "title": "向左",
        "predict": 3,
      },
      {
        "title": "向右",
        "predict": 4,
      },
    ];
  }

  /// 标题
  _buildTitle(Size size) {
    return Container(
      color: Colors.blue,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            padding: EdgeInsets.only(left: 10),
            width: size.width - 45,
            alignment: Alignment.centerLeft,
            child: Text(
              TITLE_VIDEO,
              style: TextStyle(
                fontSize: 18,
                color: AppColors.primaryElementText,
              ),
            ),
          ),
          Container(
            width: 45,
            alignment: Alignment.centerRight,
            child: IconButton(
              onPressed: () {},
              icon: Icon(
                Icons.refresh,
                color: Colors.white,
              ),
            ),
          )
        ],
      ),
    );
  }

  /// 视频窗口
  _buildVideoView(Size size) {
    return Container(
      decoration: BoxDecoration(
        boxShadow: [Shadows.primaryShadow],
        color: Colors.black,
      ),
      margin: EdgeInsets.all(5),
      child: AspectRatio(
        child: FutureBuilder(
          future: _future,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return ErrorView();
            }
            switch (snapshot.connectionState) {
              case ConnectionState.done:
                return _initPlayer(videoPlayer, size);
              case ConnectionState.none:
              case ConnectionState.waiting:
              case ConnectionState.active:
              default:
                return ProgressView();
            }
          },
        ),
        aspectRatio: 1280 / 1050,
      ),
    );
  }

  /// 控制按钮
  _buildControllButtom(List btnList) {
    var list = btnList.map((obj) {
          return ElevatedButton(
            onPressed: () async {
              R result = await VideoAPI.ptzCtrl(
                context: context,
                channel: "",
                direct: obj["predict"],
              );
              // 检查回传结果并打印
              if (HttpUtil().success(result)) {
                print(obj["title"].toString() + ":操作成功");
              }
            },
            child: Text(obj["title"]),
          );
        })?.toList() ??
        [];
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: list,
    );
  }

  @override
  void initState() {
    super.initState();
    // 调用初始化数据
    _initData();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return SafeArea(
      child: Container(
        child: Column(
          children: [
            _buildTitle(size),
            _buildVideoView(size),
            _buildControllButtom(buttonList),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    videoPlayer.dispose();
    super.dispose();
  }
}
